--[[
    author:ZYB
    time:2021-10-28 11:29:08
]]
local FOO = {_VERSION = "0.0.1"}
local type = type
local pairs = pairs
local require = require
local log = require("modules.commhm.log")

-- ! @brief 求table长度
-- ! @param table 时间戳
-- ! @return table长度
FOO.getn = function(tab)
    local n = 0
    if type(tab) == "table" then 
        for _, _ in pairs(tab) do n = n + 1 end
    end
    return n
end

-- ! @brief 深复制table
-- ! @param ori_tab 需要复制的table
-- ! @return 复制出来的table
FOO.copy = function(ori_tab)
    if (type(ori_tab) ~= "table") then return ori_tab end
    local new_tab = {};
    for i, v in pairs(ori_tab) do
        local vtyp = type(v);
        if (vtyp == "table") then
            new_tab[i] = FOO.copy(v);
        else
            new_tab[i] = v;
        end
    end
    return new_tab;
end

-- ! @brief foreach 便利table，将table的参数传给函数
-- ! @param tbl， func
FOO.foreach = function(tbl, func)
    for key, value in pairs(tbl) do func(key, value) end
end

FOO.to_list = function (tbl, func)
    local list = {}
    for key, value in pairs(tbl or {}) do
        if func then
            list[#list+1] = func(key, value)
        else
            list[#list+1] = key
        end
    end
    return list
end

FOO.trans = function(tbl, func)
    local result = {}
    for src_key, src_value in pairs(tbl or {}) do
        local dst_key, dst_value = func(src_key, src_value)
        if dst_key and dst_value then
            result[dst_key] = dst_value
        end
    end
    return result
end

FOO.clone = function(src, cmp)
    if type(src) ~= "table" then return src end

    local dst = {};
    for key, value in pairs(src or {}) do
        if not cmp or cmp(key, value) then dst[key] = FOO.clone(value) end
    end
    return dst;
end

FOO.same = function(lh, rh)
    local function table_check(src, dst)
        if not dst then return false end
        for k, v in pairs(src) do
            if type(v) == 'table' then
                if not table_check(src[k], dst[k]) then
                    return false
                end
            elseif v ~= dst[k] then
                return false
            end
        end
        return true
    end
    return table_check(lh, rh) and table_check(rh, lh)
end

return FOO
